const { secretPassword } = require('../utils/handle-password')
const userService = require('../service/userService')
class UserController {
  async createUser(ctx,next) {
    const { username,realname,telephone, password,roleId } = ctx.request.body
    const finalPassword = secretPassword(password)
    await userService.createUser(username,finalPassword,roleId,realname,telephone)
    ctx.status = 201
    ctx.body = {
      meta: {
        msg: '用户创建成功',
        status:201
      }
    }
  }
  async getUserList(ctx, next) {
    const { pagenum, pagesize, id, username, realname, telephone } = ctx.request.body
    console.log(pagenum, pagesize,id,username,realname,telephone);
    const res = await userService.getUserList(pagenum, pagesize,id,username,realname,telephone)
    ctx.body = {
      data: {
        pagenum,
        ...res
      },
      meta: {
        msg: '获取成功',
        status:200
      }
    }

  }
  async getUserById(ctx, next) {
    const { id } = ctx.params
    const res = await userService.getUserById(id)
    ctx.body = {
      data: res,
      meta: {
        msg: '查询成功',
        status:200
      }
    }
  }
  async updateUserById(ctx, next) {
    const { id } = ctx.params
    const {username,realname,roleId,telephone} = ctx.request.body
    await userService.updateUserById(id,username,realname,roleId,telephone)
    ctx.body = {
      meta: {
        msg: '更新成功',
        status:200
      }
    }
  }
  async removeUserById(ctx, next) {
    const { id } = ctx.params
    const res = await userService.removeUserById(id)
    if (res.affectedRows === 0) {
      ctx.body = {
        meta: {
          msg: '删除失败,用户不存在',
          status:500
        }
      }
      return
    }
    ctx.body = {
      data: null,
      meta: {
        msg: '删除成功',
        status:200
      }
    }
  }
  async changeUserRole(ctx, next) {
    const { id } = ctx.params
    const { rid } = ctx.request.body
    await userService.changeUserRole(id, rid)
    ctx.body = {
      meta: {
        msg: '设置角色成功',
        status:200
      }
    }
  }

}
module.exports = new UserController()